#!/usr/bin/python
# encoding: utf-8
import os
import MySQLdb
import sys
import shutil
import urllib2
import commands
import tarfile

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)

app_url="http://192.168.1.38/ambari/helloworld.war"
container_url="http://mirror.bit.edu.cn/apache/tomcat/tomcat-8/v8.5.13/bin/apache-tomcat-8.5.13.tar.gz"
dwr="/Users/konbluesky/Desktop"
# cxn = MySQLdb.Connect(host='127.0.0.1', user='root', passwd='root',charset='utf8')
BUFFER_SIZE=8192

class DownLoader(object):
    def down(self,srcurl,dest):
        url = srcurl

        file_name = url.split('/')[-1]
        u = urllib2.urlopen(srcurl)
        destfilename=dest+"/"+file_name
        f = open(destfilename, 'wb')
        meta = u.info()
        file_size = int(meta.getheaders("Content-Length")[0])

        file_size_dl = 0
        print "download starting.."
        while True:
            buffer = u.read(BUFFER_SIZE)
            if not buffer:
                break
            file_size_dl += len(buffer)
            # print 'download schedule:'+"{:.2f}".format(file_size_dl/float(file_size)*100)
            f.write(buffer)
        f.close()
        print "download ending..."
        return destfilename;

    def unzip(self,src,dest):
        # 原生命令解压
        # cmd="tar -x -f "
        # if src:
        #     cmd += src
        # if dest:
        #     cmd += dest
        #
        # (status, output)=commands.getstatusoutput(cmd)
        # print status,output

        t = tarfile.open(src)

        t.extractall(path=dest)
        return dest+"/"+src.split("/")[-1]
        #/Users/konbluesky/Desktop/apache-tomcat-8.5.13



        # stack_root="hehehehe"
        # print "{stack_root}/{version}/kafka/bin/kafka-acls.sh".format(stack_root="stack_root",version="12132")

    def deploy(self,warpath,containerpath):
        if "tomcat" in container_url:
            webapps=container_url+"/"+"webapps"
            shutil.copy(warpath,webapps)


    #
    # def dir_clean(self,dirpath,column):
    #     # 获取文件列表
    #     oldpath=basepath + dirpath
    #     filenames = os.listdir(oldpath)
    #     # 获取原目录文件总数
    #     oldcount = len(filenames)
    #     newcount = 0
    #     newdir=oldpath+"-无效/"
    #
    #     if(not os.path.exists(newdir)):
    #         os.mkdir(newdir)
    #
    #     for name in filenames:
    #         cur = cxn.cursor()
    #         cur.execute("use bstudy_sys")
    #         cur.execute("select * from student_enroll where %s='%s'" % (column,name))
    #         result=cur.fetchone()
    #         if(not result):
    #             # print result
    #             # print "找到相关记录 studentid:"+str(result[1])+"-"+result[2]
    #         # else:
    #             # print "未找到相关记录 文件名:"+name
    #             shutil.copy(oldpath+"/"+name,newdir+name)
    #             newcount+=1
    #             os.remove(oldpath+"/"+name)
    #         cur.close()
    #
    #     print "原目录:"+oldpath +" 文件总数:"+str(oldcount)+"\n"
    #     print "无效文件:"+newdir +" 文件总数:"+str(newcount)+"\n"

if __name__ == "__main__":
    dl=DownLoader()

    warpath = dl.down(app_url, dwr)

    tomcatpath = dl.down(container_url, dwr)

    container_path=dl.unzip("/Users/konbluesky/Desktop/apache-tomcat-8.5.13.tar.gz","/Users/konbluesky/Desktop")
    print warpath,tomcatpath,container_path
    dl.deploy(warpath,container_path)

